<template>
  <div>
    <c-title :hide="false" :text="title"> </c-title>

    <div class="topBox" v-if="info.avatar_image">
      <img :src="info.avatar_image" alt="" />
      <span>{{ info.username }}</span>
    </div>
    <div class="ewmBox" v-show="success">
      <canvas id="qrccode-canvas"></canvas>
    </div>
    <div class="ewmBox" v-if="$route.name === 'payCode'">
      <img :src="info.img" alt="" style="height: 16.875rem;width: 16.875rem;" />
    </div>
    <div>
      <p style="font-size: 16px; font-weight: bold; margin-bottom: 1rem;" v-show="title === '会员卡号'">{{ info.uid }}</p>
      <p style="font-size: 16px; font-weight: bold;">向收银员出示{{ title }}</p>
    </div>
  </div>
</template>

<script>
import QRCode from "qrcode";
import cTitle from "components/title";
import { Toast } from "vant";

var canvas = "";
export default {
  data() {
    return {
      info: {},
      title: "",
      success: false,
      timer: null,
      //websock
      websock: null,
      ockReconnect: false, //是否真正建立连接
      timeout: 2500, //todo 2.5秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      timeoutnum: null, //断开 重连倒计时
      isClosed: false, //是否关闭ws
      lockReconnect: false, //锁定重连状态
      maxReconnectNum: 11, //最大重连次数
      currentReconnectNum: 0 //当前重连次数
    };
  },
  mounted() {
    this.$nextTick(function() {
      // DOM操作
      canvas = document.getElementById("qrccode-canvas");
    });
  },
  activated() {
    this.info = {};
    this.title = "";
    this.success = false;
    if (this.$route.name === "codePage") {
      this.title = "支付码";
      this.getPayCode();
    } else if (this.$route.name === "payCode") {
      this.payCodePlugin();
    } else {
      this.title = "会员卡号";
      this.getMemberCode();
    }
  },
  deactivated() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    freshCode() {
      this.timer = setInterval(() => {
        if (this.$route.name === "payCode") {
          this.payCodePlugin(false);
          return;
        }
        this.getPayCode();
      }, 60000);
    },
    getMemberCode() {
      $http.get("member.member-qr-code.member-code", {}, "loading").then(
        response => {
          if (response.result === 1) {
            this.info = response.data;
            this.$nextTick(function() {
              this.createQrc(this.info.uid.toString());
            });
          } else {
            Toast(response.msg);
          }
        },
        function(response) {
          Toast(response.msg);
        }
      );
    },
    getPayCode() {
      $http.get("member.member-qr-code.pay-code", {}, "loading").then(
        response => {
          if (response.result === 1) {
            this.info = response.data;
            if (!this.timer) {
              this.freshCode();
            }
            this.$nextTick(function() {
              this.createQrc(this.info.code);
            });
          } else {
            if (this.timer) {
              clearInterval(this.timer);
            }
            Toast(response.msg);
          }
        },
        function(response) {
          if (this.timer) {
            clearInterval(this.timer);
          }
          Toast(response.msg);
        }
      );
    },
    createQrc(_url) {
      const that = this;
      QRCode.toCanvas(canvas, _url, error => {
        if (error) {
          console.log(error);
        } else {
          console.log("success");
          that.success = true;
        }
      });
    },
    // pay-code start
    async payCodePlugin(key = true) {
      let { data, msg, result } = await $http.post("plugin.pay-code.frontend.controllers.pay-code.index", {}, "");
      if (result) {
        this.fun.setWXTitle(data.plugin_name);
        this.title = data.plugin_name;
        this.info = data;
        if (key) {
          this.initWebSocket();
          if (!this.timer) {
            this.freshCode();
          }
        }
      } else {
        Toast(msg);
      }
    },
    async initWebSocket() {
      this.websock = new WebSocket(`wss://${document.location.hostname}//ws`);
      // this.websock = new WebSocket("ws://dev15.yunzmall.com//ws");
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonmessage(e) {
      console.log("接收过来的信息", e);
      if (e.data != "pong") {
        if (JSON.parse(e.data).result != 1) {
          return;
        }
        let data = JSON.parse(e.data);
        if (data.store_id && data.price) {
          this.$router.push(this.fun.getUrl("cashier_pay", { store_id: data.store_id }, { pay_code: data.pay_code, price: data.price, cashier_type: "payCode" }));
        }
      }
    },
    websocketonopen() {
      console.log("连接建立之后执行send方法发送数据");
      this.heartBeatStart();
    },
    heartBeatStart() {
      this.timeoutObj && clearTimeout(this.timeoutObj);
      this.timeoutObj = setTimeout(() => {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (this.websock.readyState == 1) {
          this.websock.send(
            JSON.stringify({
              type: "register",
              data: { group: "pay-code-update_" + this.info.uid }
            })
          );

          this.keepHeartBeat();
          this.currentReconnectNum = 0; //连接成功归零
        } else {
          console.log(this.websock);
          //否则重连
          // this.reconnect();
        }
      }, this.timeout);
    },
    keepHeartBeat() {
      this.heartBeatInterval = setInterval(() => {
        // 每隔2.8秒发送一个心跳包消息
        this.websock.send(JSON.stringify({ type: "`ping`" }));
      }, 2800);
    },
    reconnect() {
      //重新连接
      if (this.lockReconnect || this.isClosed || this.currentReconnectNum >= this.maxReconnectNum) {
        console.log("重新连接");
        if (this.websock) {
          this.websock.close();
        }
        return;
      }
      // this.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      this.timeoutnum && clearTimeout(this.timeoutnum);
      this.timeoutnum = setTimeout(() => {
        //新连接
        this.initWebSocket();
        this.lockReconnect = false;
      }, 2800);
    },
    //连接建立失败重连
    websocketonerror(e) {
      console.log("连接建立失败重连", e);
      this.isClosed = true;
    },
    websocketclose(e) {
      if (!this.isClosed) {
        this.reconnect();
      }
    }
    // pay-code end
  },
  // watch: {
  //   $route(to, from) {
  //     this.$nextTick(function() {
  //       this.createQrc();
  //     });
  //   }
  // },
  components: { cTitle }
};
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
.topBox {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 17.25rem;
  margin: 1rem auto;

  img {
    width: 3.125rem;
    height: 3.125rem;
    border-radius: 100%;
    margin: 0 0.5rem 0 0;
  }

  span {
    display: inline-block;
    color: #515a63;
    font-size: 18px;
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 超出部分显示省略号 */
    white-space: nowrap; /* 规定段落中的文本不进行换行 */
    text-align: left;
  }
}

.ewmBox {
  width: 17.25rem;
  // height: 11.25rem;
  border: 1px solid #e4e4e4;
  border-radius: 5%;
  background: #fff;
  overflow: hidden;
  margin: 2rem auto;

  p {
    color: #666;
    margin: 0.3rem auto 0;
  }

  #qrccode-canvas {
    width: 16.875rem !important;
    height: 16.875rem !important;
  }
}
</style>
